package com.yiquan.user.interceptor;

import com.alibaba.fastjson.JSON;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader("Authorization");
        if (authHeader!=null&&authHeader.startsWith("yiquan-")){
            String token = authHeader.substring(7);
            Claims claims = jwtUtil.parseJWT(token);
            if ("user".equals(claims.get("roles"))){
                String userId = claims.getId();
                claims.getSubject();
                request.setAttribute("user_claims",claims);
                request.setAttribute("userId",userId);
                return true;
            }
        }
        return responseInvalidateRequest(response,new Result(false,StatusCode.NEED_LOGIN_IN,"请登陆后再进行相关操作"));
    }

    /**
     *
     * 输出非法请求的响应
     * @param response
     * @param responseCode
     * @param msg
     * @return
     * @throws Exception
     */
    private boolean responseInvalidateRequest(HttpServletResponse response, Result result ) throws Exception{
        response.setContentType("application/json;;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(result));
        return false;
    }
}
